﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WD.Db.Contract.Model;
using WD.Web.MVC.Controllers.Filters;
using WD.Framework.Contract;
using WD.Web.MVC.Common;
using WD.Db.Contract;
using System.Globalization;
using WD.Framework.Utility;

namespace WD.Web.MVC.Areas.Manager.Controllers
{
    public class UserController : AdminControllerBase
    {
        //
        // GET: /Manager/User/
        [AdminOnlineFilter]
        public ActionResult Index(UserRequest request)
        {
            ViewBag.userId = this.CookieContext.UserName;

            request.Include = new List<string>
                {
                    "UserParent"
                };
            var result = UserService.GetUserList(request);
            return View(result);
        }


        //
        // GET: /Manager/User/Create
        [AdminOnlineFilter]
        public ActionResult Create()
        {
            //var list = Base_CodeDataService.GetBase_CodeDataListByType(CommonCode.用户类型).ToList();
            //ViewBag.list = new SelectList(list, "ID", "CodeName");
            var model = new User();
            return View("Create", model);
        }

        //
        // POST: /Manager/User/Create

        [HttpPost]
        [AdminOnlineFilter]
        public string Create(FormCollection collection)
        {
            var ajax = new AjaxResult();
            var model = new User();
            var userId = collection["UserId"];
            var cardId = collection["CardId"];
            var Pwd = collection["Pwd"];
            var WithdrawPwd = collection["WithdrawPwd"];
            var userPhone = collection["userPhone"];
            if (string.IsNullOrWhiteSpace(userId))
                return ajax.Err("请输入用户名");
            if (userId.Length < 2)
                return ajax.Err("用户名至少2个字符");
            if (string.IsNullOrWhiteSpace(Pwd))
                return ajax.Err("请输入登录密码");
            if (Pwd.Length < 6)
                return ajax.Err("用户密码至少6个字符");
            if (string.IsNullOrWhiteSpace(WithdrawPwd))
                return ajax.Err("请输入提现密码");
            if (WithdrawPwd.Length < 6)
                return ajax.Err("提现密码至少6个字符");
            if (string.IsNullOrWhiteSpace(collection["Pwd"]))
                return ajax.Err("请输入密码");
            if (string.IsNullOrWhiteSpace(collection["Pro"]))
                return ajax.Err("请选择省份");
            if (string.IsNullOrWhiteSpace(collection["City"]))
                return ajax.Err("请选择市");
            if (string.IsNullOrWhiteSpace(collection["Dis"]))
                return ajax.Err("请选择区域");
            if (string.IsNullOrWhiteSpace(collection["Name"]))
                return ajax.Err("请输入真实姓名");
            if (string.IsNullOrWhiteSpace(cardId))
                return ajax.Err("请输入身份证号");
            if (cardId.Length != 18)
                return ajax.Err("请输入正确的身份证号");
            if (string.IsNullOrWhiteSpace(userPhone))
                return ajax.Err("请输入手机号码");
            if (userPhone.Length != 11)
                return ajax.Err("请输入正确的手机号码");

            //TODO 判断用户名是否已注册
            var request = new UserRequest();
            request.UserId = userId;
            var tmp = UserService.GetUser(request);
            if (tmp != null) return ajax.Err("用户名已存在");

            //TODO 判断身份证号已被注册
            request.UserId = null;
            request.CardId = cardId;
            tmp = UserService.GetUser(request);
            if (tmp != null) return ajax.Err("此身份证号已被注册");

            //TODO 判断手机号已被注册
            request.UserId = null;
            request.CardId = null;
            request.userPhone = userPhone;
            tmp = UserService.GetUser(request);
            if (tmp != null) return ajax.Err("此手机号已被注册");

            model.userPhone = userPhone;

            TryUpdateModel(model);
            //TODO 设置管理员为邀请人
            model.UpUserId = 0;
            model.Pwd = Encrypt.MD5(model.Pwd);
            model.WithdrawPwd = Encrypt.MD5(model.WithdrawPwd);
            try
            {
                UserService.SaveUser(model, LoginInfo.LoginId);
                LoggerInsert("新增User " + JsonP(model));
            }
            catch (BusinessException e)
            {
                return ajax.Err(e.Message);
            }
            return ajax.Suc("新增信息成功!");
        }

        //
        // GET: /Manager/User/Edit/5
        [AdminOnlineFilter(Url = "/Manager/User/Edit")]
        public ActionResult Edit(int id)
        {
            //var list = Base_CodeDataService.GetBase_CodeDataListByType(CommonCode.用户类型).ToList();
            //ViewBag.list = new SelectList(list, "ID", "CodeName");
            UserRequest request = new UserRequest();
            request.Include = new List<string> { 
                "UserParent"
            };
            request.ID = id;
            var model = UserService.GetUser(id, request);
            return View("Edit", model);
        }



        //
        // POST: /Manager/User/Edit/5

        [HttpPost]
        [AdminOnlineFilter(Url = "/Manager/User/Edit_Save")]
        public string Edit(int id, FormCollection collection)
        {
            var ajax = new AjaxResult();
            var model = UserService.GetUser(id);
            TryUpdateModel(model);
            UserService.SaveUser(model, LoginInfo.LoginId);
            LoggerUpdate("更新User " + JsonP(model));
            return ajax.Suc("信息修改成功!");
        }

        //
        //用户余额充值
        // GET: /Manager/User/setUserMoney/5
        [AdminOnlineFilter(Url = "/Manager/User/setUserMoney")]
        public ActionResult setUserMoney(int id)
        {
            var model = UserService.GetUser(id);
            return View("setUserMoney", model);
        }

        [HttpPost]
        [AdminOnlineFilter(Url = "/Manager/User/setUserMoney")]
        public string setUserMoney(int id, decimal cMoney)
        {
            var model = UserService.GetUser(id);
            var ajax = new AjaxResult();
            //管理员充值
           
            return ajax.Suc("用户充值成功!");
        }

        /// <summary>
        /// 重置登录密码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// /Manager/User/setLoginPwd
        public string setLoginPwd(int id) {
            var ajax = new AjaxResult();
            var model = UserService.GetUser(id);
            model.Pwd = Encrypt.MD5("123456");
            UserService.SaveUser(model, LoginInfo.LoginId);
            LoggerUpdate("重置登录密码User " + JsonP(model));
            return ajax.Suc("登录密码重置成功!");
        }

        /// <summary>
        /// 重置交易密码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// /Manager/User/setJPwd
        public string setJPwd(int id)
        {
            var ajax = new AjaxResult();
            var model = UserService.GetUser(id);
            model.WithdrawPwd = Encrypt.MD5("123456");
            UserService.SaveUser(model, LoginInfo.LoginId);
            LoggerUpdate("重置交易密码User " + JsonP(model));
            return ajax.Suc("交易密码重置成功!");
        }

        ///
        //设置用户代理角色
        // GET: /Manager/User/Edit/5
        [AdminOnlineFilter(Url = "/Manager/User/SetUserProfit")]
        public ActionResult SetUserProfit(int id)
        {
            var request = new UserRequest();
            request.Include = new List<string> { 
                "AgentManager"
            };
            var model = UserService.GetUser(id);
            return View("SetUserProfit", model);
        }




        //
        // GET: /Manager/User/Delete/5

        [HttpPost]
        [AdminOnlineFilter(Url = "/Manager/User/Deleted")]
        public string Deleted(List<int> ids)
        {
            var ajax = new AjaxResult();
            try
            {
                UserService.DeleteUser(ids, LoginInfo.LoginId);
                LoggerDelete("删除User " + JsonP(ids));
            }
            catch (BusinessException e)
            {
                return ajax.Err(e.Message);
            }

            return ajax.Suc("信息已成功删除!");
        }

        [AdminOnlineFilter(Url = "/Manager/User/SetRole")]
        public ActionResult SetRole(int id)
        {
            var re = new BaseRequest { PageSize = 9999 };
            //需要using System.Linq;
            //获取角色的全部数据
            var rolealllist = Rbac_RoleService.GetRbac_RoleList(re).ToList();
            //获取当前要分配角色的用户
            var model = Rbac_UserService.GetRbac_User(id);
            //当前用回对应的角色信息
            var rolelist = model.Rbac_Role.ToList();

            var tmpZtreeList = rolealllist.Select(x => new ZtreeNode()
            {
                id = x.ID.ToString(CultureInfo.InvariantCulture),
                //pId=
                name = x.RoleName,
                //  open=true
                @checked = rolelist.Any(c => c.ID == x.ID)//是否选中
            }).ToList();

            //    var resultList = ToZtreeNode(tmpZtreeList, "");//转换上下级关系
            ViewBag.Nodes = JsonP(tmpZtreeList);
            ViewBag.id = id;
            return View();
        }

        [HttpPost]
        [AdminOnlineFilter(Url = "/Manager/User/SetRole")]
        public string SetRole(int id, string ids)
        {

            var ajax = new AjaxResult();
            ids = ids.TrimEnd(',');
            var idList = new List<decimal>();
            if (!string.IsNullOrWhiteSpace(ids))
            {
                idList = ids.Split(',').Select(decimal.Parse).ToList();
            }
            Rbac_UserService.SetRbac_UserRoleList(id, idList);
            return ajax.Suc("用户分配角色成功!");

        }
    }
}
